/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.web.controller;

import com.bifrost.common.constant.SessionConstant;
import com.bifrost.constant.RunningMode;
import com.bifrost.entity.Customer;
import com.bifrost.service.CustomerService;
import com.bifrost.service.RegAndLogService;
import com.bifrost.wechat.controller.AbstractOauth2Controller;
import com.bifrost.wechat.service.WxServiceContext;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 *
 *@author joewee
 *@version 1.0.0
 *@Date 2018/3/1 19:34
 */
@Controller
@RequestMapping("/wechat")
public class Oauth2Controller extends AbstractOauth2Controller {
    static  final  Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");
    private static final Logger logger = LoggerFactory.getLogger(Oauth2Controller.class);
    @Autowired
    private WxServiceContext wxServiceContext;
    @Autowired
    RegAndLogService loginService;
    @Autowired
    CustomerService customerService;
    @Value("${wechat.unionid.redirect.url:#{null}}")
    private String redirect_url;
    @Value("${running.mode:#{null}}")
    private String runningMode;
    private static final String UNION_ID_GET_URL="http://wx.e-cbest.com/Cust/GetCardTrack/GetUnionId?hash=cb";
    private static final String TEST_UNION_ID_GET_URL="http://test.wx.e-cbest.com/Cust/GetCardTrack/GetUnionId?hash=cb";

    @Override
    public String doExtension(WxMpUser user, String id ,String state,HttpServletRequest request, HttpServletResponse response) {
        logger.debug("获取的userInfo:" + user.toString());
        try {
            if(request!=null&&response!=null){
                HttpSession session = request.getSession();
                session.setAttribute(SessionConstant.OPEN_ID, user.getOpenId());
                session.setAttribute(SessionConstant.NICKNAME, user.getNickname());
                session.setAttribute(SessionConstant.SEX, user.getSex());
                session.setAttribute(SessionConstant.HEAD_IMG_URL, user.getHeadImgUrl());
                session.setAttribute(SessionConstant.CITY, user.getCity());
                session.setAttribute(SessionConstant.PROVINCE, user.getProvince());
                session.setAttribute(SessionConstant.APP_ID,id);
                //添加门店信息到session中
                session.setAttribute(SessionConstant.STORE_ID,wxServiceContext.getStoreId(id));
                //自动登录
                loginService.loginAuto(request,response);
                Customer customer = customerService.findByOpenId(user.getOpenId());
                //更新下性别前期性别设置错误，后期可删除该段代码
                customer.setCustomerGender( ""+user.getSex());
                customerService.saveCustomer(customer);

                if(customer!=null&&StringUtils.isEmpty( customer.getUnionId()))
                {
                    session.setAttribute(SessionConstant.REDIRECT_URL,encode(state));
                    if (RunningMode.DEVELOPMENT.equalsIgnoreCase(runningMode)) {
                        return String.format("redirect:%s&redirect_uri=%s",TEST_UNION_ID_GET_URL,redirect_url);
                    } else {
                        return String.format("redirect:%s&redirect_uri=%s",UNION_ID_GET_URL,redirect_url);
                    }

                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        String redirectUrl = null;
        try {
            redirectUrl = String.format("redirect:%s",encode(state));
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(),e);
        }
        if(logger.isDebugEnabled()){
            logger.debug(redirectUrl);
        }
        return redirectUrl;
    }
    /**
     * 判断字符串中是否包含中文
     * @param str
     * 待校验字符串
     * @return 是否为中文
     * @warn 不能校验是否为中文标点符号
     */
    public  boolean isContainChinese(String str) {
        Matcher m = pattern.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }
    /**
     * 校验一个字符是否是汉字
     *
     * @param c
     *  被校验的字符
     * @return true代表是汉字
     */
    public static boolean isChineseChar(char c) {
        try {
            return String.valueOf(c).getBytes("UTF-8").length > 1;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        }
    }
    private String encode(String url) throws UnsupportedEncodingException {
        char[] charArray = url.toCharArray();
        // 用于拼接过滤中文后的字符
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < charArray.length; i++) {
            char chinese = charArray[i];
            if(isChineseChar(chinese)){
                sb.append(URLEncoder.encode(String.valueOf(chinese),"utf-8"));
            }else{
                sb.append(chinese);
            }
        }
        return sb.toString();
    }
}
